package com.originskyseed.platform.job.jobhandler.task;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.job.biz.model.ReturnT;
import com.originskyseed.platform.core.job.handler.IJobHandler;
import com.originskyseed.platform.core.job.handler.annotation.JobHandler;
import com.originskyseed.platform.core.job.log.JobLogger;
import com.originskyseed.platform.task.model.TaskRelateMaintainUser;
import com.originskyseed.platform.task.service.ITaskRelateAssignPersonService;
import com.originskyseed.platform.task.service.ITaskRelateMaintainUserService;
import com.originskyseed.platform.task.service.ITaskService;
import com.originskyseed.platform.user.model.Player;
import com.originskyseed.platform.user.service.IPlayerService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 主播是否在线/主播的直播转换率/玩家是否在线
 *
 * @Author: wlj @date: 2021/4/20
 */

@Component
@JobHandler(value = "anchorIsOnLiveAndRateJobHandler")
public class AnchorIsOnLiveAndRateJobHandler extends IJobHandler {
    private static final Logger logger = LoggerFactory.getLogger(AnchorIsOnLiveAndRateJobHandler.class);

    @DubboReference
    private ITaskService taskService;

    @DubboReference
    private ITaskRelateAssignPersonService taskRelateAssignPersonService;

    @DubboReference
    private ITaskRelateMaintainUserService taskRelateMaintainUserService;

    @DubboReference
    private IUserInfoService userInfoService;

    @DubboReference
    private IPlayerService playerService;

    @Override
    public ReturnT<String> execute(String tenantCode) throws Exception {
        try {
            // 查询主播任务
            int pageSize=1;
            int pageNo=10;
            HashMap params = new HashMap<>();
            params.put("pageSize", pageSize);
            params.put("pageNo", pageNo);
            params.put("userType",1);
            BasePage<TaskRelateMaintainUser> page = new BasePage<TaskRelateMaintainUser>(pageNo, pageSize);
            page= this.taskRelateMaintainUserService.selectAnchorIsOnlineListListByPage(tenantCode,params,page);
            if (page != null && page.getTotalPage() != null && page.getTotalPage() > 0) {
                List<TaskRelateMaintainUser> results = page.getResults();
                if (results != null && results.size() > 0) {
                    //在线
                    taskRelateMaintainUserService.updateAnchorOnlineByListTenantCode(tenantCode,results);

                    //转换率
                    taskRelateMaintainUserService.updateAnchorRateByListTenantCode(tenantCode,results);
                }
                int count = page.getTotalPage();

                if (count > 1) {
                    for (int i = 2; i <= count; i++) {
                        pageNo = i;
                        params.put("pageNo", pageNo);
                        page = new BasePage<TaskRelateMaintainUser>(pageNo, pageSize);
                        page= this.taskRelateMaintainUserService.selectAnchorIsOnlineListListByPage(tenantCode,params,page);
                        results = page.getResults();
                        if (results != null && results.size() > 0) {
                            //在线
                            taskRelateMaintainUserService.updateAnchorOnlineByListTenantCode(tenantCode,results);

                            //转换率
                            taskRelateMaintainUserService.updateAnchorRateByListTenantCode(tenantCode,results);
                        }
                    }
                }
            }



            //获取玩家是否在线
            //getPlayerIsOnline(tenantCode);
        } catch (Exception e) {
            JobLogger.log("接单中心列表判断主播是否在线/主播直播转换率：" + getExceptionDetail(e));
            return FAIL;
        }
        return SUCCESS;
    }

    /**
     * 获取玩家是否在线的记录
     * @param tenantCode
     * @throws Exception
     */
    private void getPlayerIsOnline(String tenantCode) throws Exception
    {
        int pageNo=1;
        int pageSize=200;
        HashMap params = new HashMap<>();
        params.put("pageSize", pageSize);
        params.put("pageNo", pageNo);
        BasePage<Player> page = new BasePage<Player>(pageNo, pageSize);

        page = this.playerService.selectPlayerListByPageByTenantCode(tenantCode,params,page);
        if (page != null && page.getTotalPage() != null && page.getTotalPage() > 0) {
            List<Player> results = page.getResults();
            if (results != null && results.size() > 0) {
                playerService.updatePlayerIsOnLineByListTenantCode(tenantCode,results);
            }
            int count = page.getTotalPage();

            if (count > 1) {
                for (int i = 2; i <= count; i++) {
                    pageNo = i;
                    params.put("pageNo", pageNo);
                    page = new BasePage<Player>(pageNo, pageSize);
                    page = this.playerService.selectPlayerListByPageByTenantCode(tenantCode,params,page);
                    results = page.getResults();
                    if (results != null && results.size() > 0) {
                        playerService.updatePlayerIsOnLineByListTenantCode(tenantCode,results);
                    }
                }
            }
        }
    }

    /**
     * 获取异常详细信息，知道出了什么错，错在哪个类的第几行 .
     *
     * @param ex
     * @return
     */
    public static String getExceptionDetail(Exception ex) {
        String ret = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        try {
            ex.printStackTrace(pout);
            ret = new String(out.toByteArray());
        } catch (Exception e) {
        } finally {
            try {
                pout.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 分批查询
     * @param allData
     * @param size
     * @return
     */
    public List<List<String>> getSubLists(List<String> allData, int size) {
        List<List<String>> result = new ArrayList();
        for (int begin = 0; begin < allData.size(); begin = begin + size) {
            int end = (begin + size > allData.size() ? allData.size() : begin + size);
            result.add(allData.subList(begin, end));
        }
        return result;
    }

}
